/*
 * File Created: 2022-07-13 14:43:54
 * Author: yubaolin (yubaolin6@outlook.com)
 * Desc: 微应用配置
 * Last Modified: 2022-07-13 14:44:18
 * Modified By: yubaolin (yubaolin6@outlook.com>)
 */

import { MICRO_MODE, CONTAINER_ID } from './const'
import {registerMicroApps, initGlobalState } from 'qiankun'


// 设计器微应用配置
export const fsscDesignerWeb = {
  name: 'design',
  entry: import.meta.env.VITE_DESIGN_APP_HOST,
  container: '#' + CONTAINER_ID.MICRO,    // 子应用所在容器
  activeRule: ['/#/design'],   // 子应用触发规则（路径）
  // loader(){
  //   console.log(arguments)
  // }, // loading 状态发生变化时会调用的方法。
  props: {
    appId: 'design', // 可不传，默认name字段
    mode: MICRO_MODE.ROUTE, // route：子应用只渲染内容, menu-route：子应用渲染菜单
    routeBase: 'design'
  }, // 主应用需要传递给微应用的数据。
}

// 路由微应用生命周期触发事件常量定义
export const microLifeCycleEvent = {
  beforeLoad: 'micro-before-load',
  beforeMount: 'micro-before-mount',
  afterMount: 'micro-after-mount',
  beforeUnmount: 'micro-before-unmount',
  afterUnmount: 'micro-after-unmount',
}

// 微应用状态改变事件code
export const statusEventCode = 'micro-status-change'

let microCycle = function($eventBus){
  return {
    beforeLoad(app) {
      console.log(app)
      $eventBus.emit(statusEventCode, {eventCode: microLifeCycleEvent.beforeLoad, app})
      $eventBus.emit(microLifeCycleEvent.beforeLoad, app)
    },
    beforeMount(app) {
      $eventBus.emit(statusEventCode, {eventCode: microLifeCycleEvent.beforeMount, app})
      $eventBus.emit(microLifeCycleEvent.beforeMount, app)
    },
    afterMount(app) {
      $eventBus.emit(statusEventCode, {eventCode: microLifeCycleEvent.afterMount, app})
      $eventBus.emit(microLifeCycleEvent.afterMount, app)
    },
    beforeUnmount (app) {
      $eventBus.emit(statusEventCode, {eventCode: microLifeCycleEvent.beforeUnmount, app})
      $eventBus.emit(microLifeCycleEvent.beforeUnmount, app)
    },
    afterUnmount(app) {
      $eventBus.emit(statusEventCode, {eventCode: microLifeCycleEvent.afterUnmount, app})
      $eventBus.emit(microLifeCycleEvent.afterUnmount, app)
    }
  }
}

/**
 * 注册路由子应用，在挂载应用之前用，方便获取主应用的配置用于初始化
 * @param {*} mainApp
 * @param {*} state 初始化微应用状态
 */
export default function registerApps(mainApp, state) {
  const {$eventBus} = mainApp.config.globalProperties

  const apps = [
    fsscDesignerWeb
  ]
  apps.forEach(app => {
    app.props.appGlobal = mainApp.config.globalProperties
  })

  const actions = initGlobalState(state)

  microCycle = microCycle($eventBus)


  registerMicroApps(apps, microCycle)

  // 初始化全局状态，并挂载到主应用的全局上
  mainApp.config.globalProperties.$actions = actions
}

// 在组件中动态再次添加子应用
export function dynamicResisterApps(apps) {
  registerMicroApps(apps, microCycle)
}
